package com.example.caorl.job1to4.gateway.router;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 *
 */
public class RoundRobinEndpointRouter implements HttpEndpointRouter {

    public static RoundRobinEndpointRouter roundRobinEndpointRouter = new RoundRobinEndpointRouter();

    private RoundRobinEndpointRouter(){}

    public static HttpEndpointRouter getInstance(){
        return roundRobinEndpointRouter;
    }

    private static Map<String, Long> serverMap = new ConcurrentHashMap<>();

    @Override
    public String route(List<String> urls) {
        initServerMap(urls);
        List<String> servers = sortMapByValues(serverMap);
        String result = servers.get(0);
        serverMap.replace(result, serverMap.get(result)+1);
        // 请求加1
        return result;
    }

    @Override
    public void routeFinish(String url) {
        if (serverMap.containsKey(url)) {
            // 请求减一
            /*Long num = serverMap.get(url);
            if (num > 1000000) {
                serverMap.replace(url, num--);
            }*/
        }
    }


    private static void initServerMap(List<String> urls) {
        Iterator<Map.Entry<String, Long>> iterator = serverMap.entrySet().iterator();
        //移除无用服务
        while (iterator.hasNext()) {
            Map.Entry<String, Long> next = iterator.next();
            if (!urls.contains(next.getKey())) {
                iterator.remove();
            }
        }
        //新服务重新计数
        for (String url : urls) {
            if (!serverMap.containsKey(url)) {
                serverMap.put(url, 0L);
            }
        }
    }

    private static <K extends Comparable, V extends Comparable> List<K> sortMapByValues(Map<K, V> aMap) {
        List<K> finalOut = new ArrayList<>();
        aMap.entrySet()
                .stream()
                .sorted((p1, p2) -> p1.getValue().compareTo(p2.getValue()))
                .collect(Collectors.toList()).forEach(ele -> finalOut.add(ele.getKey()));
        return finalOut;
    }

    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> stringIntegerConcurrentHashMap = new ConcurrentHashMap<>();
        stringIntegerConcurrentHashMap.put("6", 4);
        stringIntegerConcurrentHashMap.put("2", 2);
        stringIntegerConcurrentHashMap.put("3", 1);
        stringIntegerConcurrentHashMap.put("8", 1);
        List<String> strings = sortMapByValues(stringIntegerConcurrentHashMap);
        System.out.println(strings.get(0));
//        System.out.println(stringIntegerMap.firstKey());

    }


}
